/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.casemain.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.CustomCheckParamUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.app.mapper.AppCaseBeforeDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.app.model.AppCaseBeforeDocumentRecord;
import com.icinfo.cloud.provider.punish.common.electricsent.vo.CaseDocumentSendinfoConfirmVo;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigFastProcedureService;
import com.icinfo.cloud.provider.punish.config.vo.ConfigBusiParamDocumentInfoVo;
import com.icinfo.cloud.provider.punish.config.vo.ConfigFastProcedureVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.AttachmentTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseAppendixRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainEvidenceService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainEvidenceVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesDetailInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseAppendAppendixRecordDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseRelateDocumentInfoDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseZlgzDocumentInfoDto;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentSendinfoConfirm;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.cloud.xzcf.provider.member.zfpeople.dto.ZfPeopleBaseInfoVO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import org.apache.commons.compress.utils.Lists;
import org.checkerframework.checker.units.qual.C;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述: 案件证据表-trj case_main_evidence 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月15日
 */
@Service
public class CaseMainEvidenceServiceImpl extends MyBatisServiceSupport implements ICaseMainEvidenceService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseMainEvidenceServiceImpl.class);

    @Value("${evidence.url}")
    private String url;

    @Value("${evidence.api.evidencePageList}")
    private String evidencePageList;

    @Value("${evidence.api.deleteDraft}")
    private String deleteDraft;

    @Value("${evidence.api.caseSave}")
    private String synchronizationUrl;

    private final String CODE = "code";

    private final String DATA = "data";

    private final String DL = "dataList";

    private final Integer TWO_HUNDRED = 200;

    @Resource
    private CaseMainEvidenceMapper caseMainEvidenceMapper;

    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;

    @Resource
    private CaseAppendixRecordMapper caseAppendixRecordMapper;

    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;

    @Resource
    private ICasePartiesRecordService casePartiesRecordService;

    @Resource
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;

    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;

    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;

    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;

    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;

    @Resource
    private CaseOfflineDocumentRecordMapper caseOfflineDocumentRecordMapper;

    @Resource
    private AppCaseBeforeDocumentRecordMapper appCaseBeforeDocumentRecordMapper;

    @Resource
    private CaseRelatedDocumentRecordMapper caseRelatedDocumentRecordMapper;

    @Resource
    private ICaseMainInfoService caseMainInfoService;

    @Resource
    private ICaseAppendixRecordService caseAppendixRecordService;

    @Resource
    private IConfigFastProcedureService configFastProcedureService;

    @Override
    public PageResponse<CaseMainEvidenceVo> getEvidenceList(CaseEvidenceShareQueryDto caseEvidenceShareQueryDto) {
        PageResponse<CaseMainEvidenceVo> page = new PageResponse<>();
        JSONObject param = new JSONObject();
        param.put("caseId", caseEvidenceShareQueryDto.getCaseId());
        param.put("pageSize", "20000");
        param.put("pageNum", "1");
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createPost(url.concat(evidencePageList)).body(param.toJSONString()).headerMap(headers,true).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        List<CaseMainEvidenceVo> list = new ArrayList<>();
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            JSONArray array = info.getJSONObject(DATA).getJSONArray(DL);
            page.setRecordsTotal(array.size());
            //page.setPages(array.size()/caseEvidenceShareQueryDto.getLength());
            for (int i = 0; i < array.size(); i++) {
                CaseMainEvidenceVo caseMainEvidenceVo = JSON.parseObject(array.getJSONObject(i).toJSONString(), CaseMainEvidenceVo.class);
                caseMainEvidenceVo.setCaseId(caseEvidenceShareQueryDto.getCaseId());
                list.add(caseMainEvidenceVo);
            }
        } else {
            logger.info(evidencePageList.concat(" response:"),response);
        }
        if (!list.isEmpty()) {
            // 先删除
            caseMainEvidenceMapper.deleteAll(caseEvidenceShareQueryDto.getCaseId());
            // 保存
            caseMainEvidenceMapper.savaList(list);
            // 分页
            list = list.stream().skip((caseEvidenceShareQueryDto.getPageNum() - 1) * caseEvidenceShareQueryDto.getLength()).limit(caseEvidenceShareQueryDto.getLength()).collect(Collectors.toList());
            page.setData(list);
        }
        return page;
    }

    @Override
    public Boolean removeShareEvidence(String uid) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        JSONObject json = new JSONObject();
        json.put("uid", uid);
        String response = HttpUtil.createPost(url.concat(deleteDraft)).body(json.toJSONString()).headerMap(headers,true).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return caseMainEvidenceMapper.deleteByPrimaryKey(uid) == 1;
        } else {
            logger.info(deleteDraft.concat(" response:"),response);
        }
        return false;
    }

    @Override
    public Boolean synchronizationCaseInfo(String caseId) {
        JSONObject param = new JSONObject();
        CaseDetailInfoQueryDto caseDetailInfoQueryDto = new CaseDetailInfoQueryDto();
        caseDetailInfoQueryDto.setCaseId(caseId);
        setSynParam(param, caseId);

        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createPost(url.concat(synchronizationUrl)).body(param.toJSONString()).headerMap(headers,true).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        } else {
            logger.info(synchronizationUrl.concat(" response:"),response);
        }
        return false;
    }

    @Override
    public String getEvidenceNameStr(String caseId) {
        CaseMainEvidence param = new CaseMainEvidence();
        param.setCaseId(caseId);
        param.setEvidenceStatus("02");
        List<CaseMainEvidence> caseMainEvidences = caseMainEvidenceMapper.select(param);
        StringJoiner stringJoiner = new StringJoiner(",");
        caseMainEvidences = caseMainEvidences.stream().sorted(Comparator.comparing(CaseMainEvidence::getCreateTime)).collect(Collectors.toList());
        for (CaseMainEvidence evidence : caseMainEvidences) {
            stringJoiner.add(evidence.getEvidenceName());
        }
        CaseMainInfo caseMainInfo=caseMainInfoMapper.selectByPrimaryKey(caseId);
        if(Constant.STRING_3.equals(caseMainInfo.getCaseType())){
            List<ConfigBusiParamDocumentInfoVo> list = caseDocumentRecordMapper.getQuickEvidenceName(caseId);
            for (ConfigBusiParamDocumentInfoVo configBusiParamDocumentInfoVo : list) {
                if(StringUtils.isNotBlank(configBusiParamDocumentInfoVo.getDocumentCatalogName())) {
                    stringJoiner.add(configBusiParamDocumentInfoVo.getDocumentCatalogName());
                }
            }
        }
        return stringJoiner.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appendEvidence(CaseAppendEvidenceDto caseAppendEvidenceDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtil.isEmpty(userInfo)) {
            throw new BusinessException("未登录或登录信息已失效");
        }
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseAppendEvidenceDto.getCaseId());

        // 如果走处罚告知则进行必传校验
        if(Constant.STRING_2.equals(caseAppendEvidenceDto.getSimpleCaseStage())){
            Example reasonExample=new Example(CaseReasonMainRecord.class);
            reasonExample.createCriteria().andEqualTo("caseId",caseAppendEvidenceDto.getCaseId()).andEqualTo("status","1");
            List<CaseReasonMainRecord> caseReasonMainRecords=caseReasonMainRecordMapper.selectByExample(reasonExample);
            if(ObjectUtil.isEmpty(caseReasonMainRecords)){
                throw new BusinessException("未找到对应案由编码");
            }
            ConfigFastProcedureVo configFastProcedureVo = configFastProcedureService.getTemplateByListCode(caseMainInfo.getCaseOrgCode(), caseReasonMainRecords.get(0).getCaseReasonCode());
            // 线下和关联都没有进行校验
            if(Constant.STRING_1.equals(configFastProcedureVo.getIsRectify()) && (ObjectUtil.isEmpty(caseAppendEvidenceDto.getCaseZlgzDocumentInfo().getCaseZlzgRelateDocumentInfo()) && ObjectUtil.isEmpty(caseAppendEvidenceDto.getCaseZlgzDocumentInfo().getCaseZlzgOfflineDocumentInfo()))){
                throw new BusinessException("责令改正通知书必填");
            }
            checkDocumentIsRequired(configFastProcedureVo.getKyblIsRequired(), caseAppendEvidenceDto.getCaseKyblAppendixRecord(), AttachmentTypeEnum.ATTACHTYPE90);
            checkDocumentIsRequired(configFastProcedureVo.getRecordIsRequired(), caseAppendEvidenceDto.getCaseXwblAppendixRecord(), AttachmentTypeEnum.ATTACHTYPE7);
            checkDocumentIsRequired(configFastProcedureVo.getSfzmIsRequired(), caseAppendEvidenceDto.getCaseSfzmAppendixRecord(), AttachmentTypeEnum.ATTACHTYPE92);
            checkDocumentIsRequired(configFastProcedureVo.getXcsytIsRequired(), caseAppendEvidenceDto.getCaseXcsytAppendixRecord(), AttachmentTypeEnum.ATTACHTYPE93);
            checkDocumentIsRequired(configFastProcedureVo.getXczpjsmIsRequired(), caseAppendEvidenceDto.getCaseXczpAppendixRecord(), AttachmentTypeEnum.ATTACHTYPE91);
        }
        setAttachmentType(caseAppendEvidenceDto.getCaseKyblAppendixRecord(), AttachmentTypeEnum.ATTACHTYPE90);
        setAttachmentType(caseAppendEvidenceDto.getCaseXwblAppendixRecord(), AttachmentTypeEnum.ATTACHTYPE7);
        setAttachmentType(caseAppendEvidenceDto.getCaseSfzmAppendixRecord(), AttachmentTypeEnum.ATTACHTYPE92);
        setAttachmentType(caseAppendEvidenceDto.getCaseXcsytAppendixRecord(), AttachmentTypeEnum.ATTACHTYPE93);
        setAttachmentType(caseAppendEvidenceDto.getCaseXczpAppendixRecord(), AttachmentTypeEnum.ATTACHTYPE91);

        delDocumentAndAppendix(caseAppendEvidenceDto.getCaseId(), caseMainInfo.getCaseCurrentStageCode());
        // 保存线下责令整改通知书
        if(ObjectUtil.isNotEmpty(caseAppendEvidenceDto.getCaseZlgzDocumentInfo().getCaseZlzgOfflineDocumentInfo())){
            for (CaseOfflineDocumentSaveDto caseOfflineDocumentSaveDto:
            caseAppendEvidenceDto.getCaseZlgzDocumentInfo().getCaseZlzgOfflineDocumentInfo()) {
                ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_ZLGZTZS.getCode());
                CaseOfflineDocumentRecord offlineDocumentRecord = new CaseOfflineDocumentRecord();
                BeanUtils.copyProperties(caseOfflineDocumentSaveDto, offlineDocumentRecord);
                offlineDocumentRecord.setCaseId(caseAppendEvidenceDto.getCaseId());
                offlineDocumentRecord.setDocumentKindCode(DocumentKindEnum.DOC_KIND_ZLGZTZS.getCode());
                offlineDocumentRecord.setDocumentKindName(DocumentKindEnum.DOC_KIND_ZLGZTZS.getDes());
                offlineDocumentRecord.setDocumentType(configBusiParamDocumentInfo.getDocumentType());
                offlineDocumentRecord.setDocumentDesc(DocumentKindEnum.DOC_KIND_ZLGZTZS.getDes());
                offlineDocumentRecord.setDocumentTittle(DocumentKindEnum.DOC_KIND_ZLGZTZS.getDes());
                offlineDocumentRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                offlineDocumentRecord.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                offlineDocumentRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                offlineDocumentRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                offlineDocumentRecord.setCreateUserId(userInfo.getUserId().toString());
                offlineDocumentRecord.setCreateUserName(userInfo.getRealName());
                offlineDocumentRecord.setStatus(Constant.STRING_1);
                offlineDocumentRecord.setId(StringUtils.uuid());
                offlineDocumentRecord.setCreateTime(LocalDateTime.now());
                caseOfflineDocumentRecordMapper.insertSelective(offlineDocumentRecord);
            }

        }
        // 关联文书
        if(ObjectUtil.isNotEmpty(caseAppendEvidenceDto.getCaseZlgzDocumentInfo().getCaseZlzgRelateDocumentInfo())){
            for (CaseRelateDocumentInfoDto caseRelateDocumentInfoDto :
            caseAppendEvidenceDto.getCaseZlgzDocumentInfo().getCaseZlzgRelateDocumentInfo()) {
                CaseRelateDocumentInfoDto relateDocumentInfoDto = caseRelateDocumentInfoDto;
                CaseRelatedDocumentRecord record = new CaseRelatedDocumentRecord();
                record.setCaseId(caseAppendEvidenceDto.getCaseId());
                record.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                record.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                record.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                record.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                record.setCreateUserId(userInfo.getUserId().toString());
                record.setCreateUserName(userInfo.getRealName());
                CustomCheckParamUtil.doCheck(relateDocumentInfoDto);
                CasePartiesRecord partiesRecord = casePartiesRecordService.getCasePartiesRecordByIdentityCode(caseAppendEvidenceDto.getCaseId(),relateDocumentInfoDto.getPartyIdentityCode(), relateDocumentInfoDto.getPartyType(), null);
                if (ObjectUtils.isEmpty(partiesRecord)) {
                    throw new BusinessException("该文书不是案件当事人的文书");
                }
                // 查询业务关联文书配置
                ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(relateDocumentInfoDto.getDocumentCatalogCode());

                record.setCreateTime(LocalDateTime.now());
                record.setId(BaseUtil.createUid());
                record.setDocumentKindCode(configBusiParamDocumentInfo.getDocumentKindCode());
                record.setDocumentKindName(configBusiParamDocumentInfo.getDocumentKindName());
                record.setDocumentType(relateDocumentInfoDto.getDocumentType());
                record.setDocumentId(relateDocumentInfoDto.getDocumentId());
                record.setPartyId(partiesRecord.getPartyId());
                record.setRelatedType(Constant.STRING_1);
                caseRelatedDocumentRecordMapper.insertSelective(record);
            }
        }
        // 保存立案审批表附件
        appendAppendixRecords(caseAppendEvidenceDto.getCaseId(), caseAppendEvidenceDto.getCaseKyblAppendixRecord(), caseMainInfo);
        appendAppendixRecords(caseAppendEvidenceDto.getCaseId(), caseAppendEvidenceDto.getCaseSfzmAppendixRecord(), caseMainInfo);
        appendAppendixRecords(caseAppendEvidenceDto.getCaseId(), caseAppendEvidenceDto.getCaseXcsytAppendixRecord(), caseMainInfo);
        appendAppendixRecords(caseAppendEvidenceDto.getCaseId(), caseAppendEvidenceDto.getCaseXwblAppendixRecord(), caseMainInfo);
        appendAppendixRecords(caseAppendEvidenceDto.getCaseId(), caseAppendEvidenceDto.getCaseXczpAppendixRecord(), caseMainInfo);
        // 更新案件detail的表单状态和案件状态
        CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
        updateCaseMainDetailInfo.setCaseId(caseAppendEvidenceDto.getCaseId());
        updateCaseMainDetailInfo.setSimpleFormType(caseAppendEvidenceDto.getSimpleFormType());
        updateCaseMainDetailInfo.setSimpleCaseStage(caseAppendEvidenceDto.getSimpleCaseStage());
        caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
    }

    /**
     * 删除相关附件和关联文书
     * @param caseId
     * @param currentStageCode
     * @author sunjiefei
     * @date 2023-05-04
     */
    private void delDocumentAndAppendix(String caseId, String currentStageCode) {
        Example exampleOffline = new Example(CaseOfflineDocumentRecord.class);
        exampleOffline.createCriteria().andEqualTo("documentKindCode", DocumentKindEnum.DOC_KIND_ZLGZTZS.getCode())
                .andEqualTo("caseId", caseId)
                .andEqualTo("status", "1");
        caseOfflineDocumentRecordMapper.deleteByExample(exampleOffline);
        Example exampleRelate = new Example(CaseRelatedDocumentRecord.class);
        exampleRelate.createCriteria().andEqualTo("caseStageCode", currentStageCode)
                .andEqualTo("caseId", caseId)
                .andEqualTo("relatedType", Constant.STRING_1);
        caseRelatedDocumentRecordMapper.deleteByExample(exampleRelate);
        Example exampleAppendixRecord = new Example(CaseAppendixRecord.class);
        exampleAppendixRecord.createCriteria().andEqualTo("caseStageCode", currentStageCode)
                .andEqualTo("caseId", caseId).andEqualTo("isDelete", Constant.STRING_0)
                .andEqualTo("uploadType", Constant.STRING_3);
        caseAppendixRecordMapper.deleteByExample(exampleAppendixRecord);
    }

    @Override
    public CaseAppendEvidenceDto getAppendEvidence(String caseId) {
        if (ObjectUtil.isEmpty(caseId)) {
            throw new BusinessException("案件id不能为空");
        }
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseId);
        CaseAppendEvidenceDto caseAppendEvidenceDto = new CaseAppendEvidenceDto();
        caseAppendEvidenceDto.setCaseId(caseId);
        CaseZlgzDocumentInfoDto caseZlgzDocumentInfo = new CaseZlgzDocumentInfoDto();
        Example exampleOffline = new Example(CaseOfflineDocumentRecord.class);
        exampleOffline.createCriteria().andEqualTo("documentKindCode", DocumentKindEnum.DOC_KIND_ZLGZTZS.getCode())
                .andEqualTo("caseId", caseId)
                .andEqualTo("status", "1");
        List<CaseOfflineDocumentRecord> caseOfflineDocumentRecords = caseOfflineDocumentRecordMapper.selectByExample(exampleOffline);
        List<CaseOfflineDocumentSaveDto> caseZlzgOfflineDocumentInfo = BaseUtil.copyListProperties(caseOfflineDocumentRecords, CaseOfflineDocumentSaveDto.class);
        caseZlgzDocumentInfo.setCaseZlzgOfflineDocumentInfo(caseZlzgOfflineDocumentInfo);

        Example exampleRelate = new Example(CaseRelatedDocumentRecord.class);
        exampleRelate.createCriteria().andEqualTo("caseStageCode", caseMainInfo.getCaseCurrentStageCode())
                .andEqualTo("caseId", caseId);
        List<CaseRelatedDocumentRecord> caseRelatedDocumentRecords = caseRelatedDocumentRecordMapper.selectByExample(exampleRelate);

        List<CaseRelateDocumentInfoDto> caseZlzgRelateDocumentInfo = getRelateDocumentInfo(caseRelatedDocumentRecords);
        caseZlgzDocumentInfo.setCaseZlzgOfflineDocumentInfo(caseZlzgOfflineDocumentInfo);
        caseZlgzDocumentInfo.setCaseZlzgRelateDocumentInfo(caseZlzgRelateDocumentInfo);
        caseAppendEvidenceDto.setCaseZlgzDocumentInfo(caseZlgzDocumentInfo);
        caseAppendEvidenceDto.setCaseKyblAppendixRecord(getAppendixRecords(caseId, caseMainInfo.getCaseCurrentStageCode(), AttachmentTypeEnum.ATTACHTYPE90));
        caseAppendEvidenceDto.setCaseXwblAppendixRecord(getAppendixRecords(caseId, caseMainInfo.getCaseCurrentStageCode(), AttachmentTypeEnum.ATTACHTYPE7));
        caseAppendEvidenceDto.setCaseSfzmAppendixRecord(getAppendixRecords(caseId, caseMainInfo.getCaseCurrentStageCode(), AttachmentTypeEnum.ATTACHTYPE92));
        caseAppendEvidenceDto.setCaseXcsytAppendixRecord(getAppendixRecords(caseId, caseMainInfo.getCaseCurrentStageCode(), AttachmentTypeEnum.ATTACHTYPE93));
        caseAppendEvidenceDto.setCaseXczpAppendixRecord(getAppendixRecords(caseId, caseMainInfo.getCaseCurrentStageCode(), AttachmentTypeEnum.ATTACHTYPE91));
        caseAppendEvidenceDto.setSimpleCaseStage(caseMainDetailInfo == null ? "" : caseMainDetailInfo.getSimpleCaseStage());
        caseAppendEvidenceDto.setSimpleFormType(caseMainDetailInfo == null ? "" : caseMainDetailInfo.getSimpleFormType());
        return caseAppendEvidenceDto;
    }

    /**
     * 获取关联文书信息
     * @param caseRelatedDocumentRecords
     * @return: java.util.List<com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseRelateDocumentInfoDto>
     * @author sunjiefei
     * @date 2023-05-05
     */
    private List<CaseRelateDocumentInfoDto> getRelateDocumentInfo(List<CaseRelatedDocumentRecord> caseRelatedDocumentRecords){
        if(ObjectUtils.isEmpty(caseRelatedDocumentRecords)){
            return Lists.newArrayList();
        }else{
            List<CaseRelateDocumentInfoDto> caseRelateDocumentInfo = new ArrayList<>();
            caseRelatedDocumentRecords.forEach(s->{
                CaseRelateDocumentInfoDto caseRelateDocumentInfoDto = new CaseRelateDocumentInfoDto();
                caseRelateDocumentInfoDto.setDocumentId(s.getDocumentId());
                caseRelateDocumentInfoDto.setDocumentType(s.getDocumentType());
                AppCaseBeforeDocumentRecord documentRecordVo = appCaseBeforeDocumentRecordMapper.selectByPrimaryKey(s.getDocumentId());
                caseRelateDocumentInfoDto.setDocumentCatalogCode(documentRecordVo.getDocumentCatalogCode());
                caseRelateDocumentInfoDto.setDocumentCatalogName(documentRecordVo.getDocumentName());
                caseRelateDocumentInfoDto.setDocumentNumber(documentRecordVo.getDocumentNumber());
                caseRelateDocumentInfoDto.setDocumentUrl(documentRecordVo.getDocumentUrl());
                CasePartiesRecordVo casePartiesRecordVo = casePartiesRecordService.getCasePartiesInfoByPartyId(s.getCaseId(), s.getPartyId());
                caseRelateDocumentInfoDto.setPartyIdentityCode(casePartiesRecordVo.getPartyIdentityCode());
                caseRelateDocumentInfoDto.setPartyIdentityType(casePartiesRecordVo.getPartyIdentityType());
                caseRelateDocumentInfoDto.setPartyName(casePartiesRecordVo.getPartyName());
                caseRelateDocumentInfoDto.setPartyType(casePartiesRecordVo.getPartyType());
                caseRelateDocumentInfo.add(caseRelateDocumentInfoDto);
            });
            return caseRelateDocumentInfo;
        }
    }

    /**
     * 获取补充证据附件
     * @param caseId
     * @param currentStageCode
     * @param attachmentTypeEnum
     * @author sunjiefei
     * @date 2023-05-04
     */
    private CaseAppendAppendixRecordDto getAppendixRecords(String caseId, String currentStageCode, AttachmentTypeEnum attachmentTypeEnum){
        CaseAppendAppendixRecordDto caseAppendAppendixRecordDto = new CaseAppendAppendixRecordDto();
        Example exampleAppendixRecord = new Example(CaseAppendixRecord.class);
        exampleAppendixRecord.createCriteria().andEqualTo("caseStageCode", currentStageCode)
                .andEqualTo("caseId", caseId).andEqualTo("isDelete", Constant.STRING_0)
                .andEqualTo("uploadType", Constant.STRING_3).andEqualTo("appendixTypeId", attachmentTypeEnum.getCode());
        List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(exampleAppendixRecord);
        List<EvidenceAppendixRecordDto> appendixRecords = BaseUtil.copyListProperties(caseAppendixRecords, EvidenceAppendixRecordDto.class);
        caseAppendAppendixRecordDto.setAppendixRecords(appendixRecords);
        return caseAppendAppendixRecordDto;
    }

    /**
     * 追加证据附件
     * @param caseId
     * @param caseAppendixRecord
     * @param caseMainInfo
     * @author sunjiefei
     * @date 2023-04-23
     */
    private void appendAppendixRecords(String caseId, CaseAppendAppendixRecordDto caseAppendixRecord, CaseMainInfoVo caseMainInfo){
        if(ObjectUtil.isNotEmpty(caseAppendixRecord) && ObjectUtil.isNotEmpty(caseAppendixRecord.getAppendixRecords())){
            ConfigBusiParamDocumentInfo paramDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_LASPB.getCode());
            String documentCatalogCode = paramDocumentInfo == null ? "" : paramDocumentInfo.getDocumentCatalogCode();
            caseAppendixRecord.getAppendixRecords().stream().forEach(s->{
                CaseAppendixRecord record = new CaseAppendixRecord();
                BeanUtils.copyProperties(s, record);
                record.setCaseId(caseId);
                record.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                record.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                record.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                record.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                record.setUploadType(Constant.STRING_3);
                record.setDocumentCatalogCode(documentCatalogCode);
                caseAppendixRecordService.saveCaseAppendixRecord(record);
            });
        }
    }

    /**
     * 根据事项配置校验文书是否必填
     * @param required
     * @param caseAppendixRecord
     * @param attachmentTypeEnum
     * @author sunjiefei
     * @date 2023-04-19
     */
    private void checkDocumentIsRequired(String required, CaseAppendAppendixRecordDto caseAppendixRecord, AttachmentTypeEnum attachmentTypeEnum){
        if (ObjectUtil.isEmpty(caseAppendixRecord) || ObjectUtil.isEmpty(caseAppendixRecord.getAppendixRecords())){
            if(Constant.STRING_1.equals(required)){
                throw new BusinessException(attachmentTypeEnum.getDes()+"必填");
            }
        }
    }

    /**
     * 设置文件类型
     * @param caseAppendixRecord
     * @param attachmentTypeEnum
     * @author sunjiefei
     * @date 2023-04-24
     */
    private void setAttachmentType(CaseAppendAppendixRecordDto caseAppendixRecord, AttachmentTypeEnum attachmentTypeEnum){
        if (ObjectUtil.isNotEmpty(caseAppendixRecord) && ObjectUtil.isNotEmpty(caseAppendixRecord.getAppendixRecords())){
            caseAppendixRecord.getAppendixRecords().stream().forEach(s->s.setAppendixTypeId(attachmentTypeEnum.getCode()));
        }
    }

    /**
     * 设置请求参数
     * @param param
     * @param caseId
     */
    private void setSynParam( JSONObject param, String caseId) {
        //        "caseId": "案件id",
//        "caseNo": "案件编号",
//        "caseName": "案件名称",
//        "caseTime": "案发时间",
//        "cpType": "当事人类型（01=公民，02=法人，03=其他组织，04=个体工商户）",
//        "cpName": "当事人名称",
//        "cpCertType": "当事人证件类型 syn_code_cert",
//        "cpCertNo": "当事人证件编号",
//        "cpTel": "当事人联系电话",
//        "lerepCertType": "法定代表人证件类型 syn_code_cert",
//        "lerepName": "法定代表人姓名",
//        "lerepCertNo": "法定代表人证件号码",
//        "addressLive": "住所（住址）",
//        "areaNameLive": "住所区划名称",
//        "areaCodeLive": "住所区划编码",
//        "addressRegisterd": "注册地址",
//        "areaCodeRegisterd": "注册地址区划编码",
//        "areaNameRegisterd": "注册地址区划名称",
//        "addressOperating": "经营地址",
//        "areaCodeOperating": "经营地址区划编码",
//        "areaNameOperating": "经营地址区划名称",
//        "zfPersonnelName": "执法人员姓名 至少具备两名执法人员，以“^”分隔",
//        "zfPersonnelCode": "执法人员证件编号 与执法人员姓名对应，以“^”分隔",
//        "caseDesc": "案情介绍",
//        "caseCrimePlace": "案发地",
//        "areaCodeCaseCrimePlace": "案发地区划编码",
//        "areaNameCaseCrimePlace": "案发地区划名称",
//        "lawDeptCode": "执法单位统一社会信用编码（机构）",
//        "lawDeptName": "执法单位名称（机构）",
//        "lawDeptOrgCode": "执法单位机构编码（机构）",
//        "zfDeptCode": "执法单位机构部门编码（部门）",
//        "zfDeptName": "执法单位机构部门名称（部门）"
        param.put("caseId", caseId);

        CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
        caseMainDetailInfo.setCaseId(caseId);
        param.put("caseName", mainInfo.getCaseName());
        CaseMainDetailInfo caseMainDetailInfos =  caseMainDetailInfoMapper.select(caseMainDetailInfo).get(0);
        param.put("caseNo", mainInfo.getCaseNumber());
        param.put("caseTime", caseMainDetailInfos.getCaseHappenTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        CasePartiesDetailInfoVo casePartiesInfo = casePartiesRecordService.getCasePartiesDetailInfo(caseId);
        param.put("cpType", PartyTypeEnum.PERSON.getCode().equals(casePartiesInfo.getPartyType()) ? "01" : "02");
        param.put("cpName", PartyTypeEnum.PERSON.getCode().equals(casePartiesInfo.getPartyType()) ? casePartiesInfo.getCasePartiesPersonInfo().getName() : casePartiesInfo.getCasePartiesLegalInfo().getEntName());

        List<CasePartiesRecordVo> casePartiesRecord = casePartiesRecordService.getCasePartiesInfo(caseId);
        param.put("cpCertNo", casePartiesRecord.get(0).getPartyIdentityCode());
        param.put("cpTel", PartyTypeEnum.PERSON.getCode().equals(casePartiesInfo.getPartyType()) ? casePartiesInfo.getCasePartiesPersonInfo().getMobile() : casePartiesInfo.getCasePartiesLegalInfo().getPhone());
        /**当事人身份证件类型：111-居民身份证，112-临时居民身份证，113-户口簿，114-中国人民解放军军官证，115-中国人民武装警察部队警官证，
         * 117-出生医学证明，118-中国人民解放军士兵证，119-中国人民武装警察部队士兵证，120-中国人民解放军文职人员证，
         * 122-中国人民武装警察部队文职人员证，154-居住证，411-外交护照，412-公务护照，413-公务普通护照，414-普通护照，415-旅行证，
         * 511-台湾居民来往大陆通行证，516-港澳居民来往内地通行证*/
        param.put("cpCertType", "111");
        param.put("lerepCertType", "111");
        param.put("lerepName", PartyTypeEnum.LEGAL.getCode().equals(casePartiesInfo.getPartyType()) ? casePartiesInfo.getCasePartiesLegalInfo().getLegalName() : "");
        param.put("lerepCertNo", PartyTypeEnum.LEGAL.getCode().equals(casePartiesInfo.getPartyType()) ? casePartiesInfo.getCasePartiesLegalInfo().getLegalCertNo() : "");
        param.put("addressLive", PartyTypeEnum.LEGAL.getCode().equals(casePartiesInfo.getPartyType()) ? casePartiesInfo.getCasePartiesLegalInfo().getAddress() : casePartiesInfo.getCasePartiesPersonInfo().getAddress());
        param.put("cpCertType", PartyTypeEnum.LEGAL.getCode().equals(casePartiesInfo.getPartyType()) ? "001" : "111");
        // 单位特殊处理
        param.put("cpCertNo", PartyTypeEnum.LEGAL.getCode().equals(casePartiesInfo.getPartyType()) ? casePartiesInfo.getCasePartiesLegalInfo().getUniscid() : casePartiesRecord.get(0).getPartyIdentityCode());
        param.put("areaNameLive", "");
        param.put("areaCodeLive", "");
        param.put("addressRegisterd",  PartyTypeEnum.LEGAL.getCode().equals(casePartiesInfo.getPartyType()) ? casePartiesInfo.getCasePartiesLegalInfo().getAddress() : "");
        param.put("areaCodeRegisterd", "");
        param.put("areaNameRegisterd", "");
        param.put("addressOperating", PartyTypeEnum.LEGAL.getCode().equals(casePartiesInfo.getPartyType()) ? casePartiesInfo.getCasePartiesLegalInfo().getAddress() : "");
        param.put("areaCodeOperating", "");
        param.put("areaNameOperating", "");

        param.put("zfPersonnelName", "");
        param.put("zfPersonnelCode", "");
        // 设置执法人员信息
        setZfInfo(param,caseId);
        param.put("caseDesc", caseMainDetailInfos.getCaseConciseCondition());
        param.put("caseCrimePlace", caseMainDetailInfos.getCaseHappenAddressDetail());
        param.put("areaCodeCaseCrimePlace", caseMainDetailInfos.getCaseHappenAddressAreaCode());
        param.put("areaNameCaseCrimePlace", "");
        UserDTO userDTO = UserUtil.getUserInfo();
        param.put("lawDeptCode", StringUtils.isNotBlank(mainInfo.getCaseOrgCode()) ? mainInfo.getCaseOrgCode().substring(13) : mainInfo.getCaseOrgCode());
        param.put("lawDeptName", userDTO.getOrgName());
        param.put("lawDeptOrgCode", userDTO.getOrgCode());
        param.put("zfDeptCode", userDTO.getDeptCode());
        param.put("zfDeptName", userDTO.getDeptName());
    }
    /**
     * 设置执法人员信息
     * @param param
     * @param
     */
    private void setZfInfo(JSONObject param, String caseId) {
        CaseHandlePersonRecord handlePersonRecord = new CaseHandlePersonRecord();
        handlePersonRecord.setCaseId(caseId);
        handlePersonRecord.setStatus(Constant.STRING_1);
        List<CaseHandlePersonRecord> handlePersonRecords = caseHandlePersonRecordMapper.select(handlePersonRecord);
        if (!handlePersonRecords.isEmpty()){
            StringJoiner stringJion = new StringJoiner("^");
            StringJoiner stringJion1 = new StringJoiner("^");
            StringJoiner stringJion2 = new StringJoiner(",");
            for (CaseHandlePersonRecord caseHandlePersonRecord : handlePersonRecords){
                stringJion.add(caseHandlePersonRecord.getHandlePersonName());
                stringJion2.add(caseHandlePersonRecord.getHandlePersonId());
            }
            param.put("zfPersonnelName", stringJion.toString());
            // 不掉接口，拼userId
            // 查询执法证号
            JSONObject baseInfoRequest = new JSONObject();
            List<String> userIds = new ArrayList<>();
            userIds.addAll(Arrays.asList(stringJion2.toString().split(",")));
            baseInfoRequest.put("userIds", userIds);
            List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
            for (int i = 0; i < baseInfo.size(); i++) {
                stringJion1.add(baseInfo.get(i).getZfCertList().get(0).getZfCertNo());
            }
            param.put("zfPersonnelCode", stringJion1.toString());
        }
    }


}
